# -*- coding: utf-8 -*-
import ctypes
import json
import os
import random
import re
import time
import urllib
import uuid
from datetime import datetime, timezone
from urllib.parse import urlencode, urljoin, quote

# import requests
import  requests
from PyQt5 import QtTest
from PyQt5.QtWidgets import QApplication
# from requests.adapters import HTTPAdapter

from config import global_config
from core import Cipher, sign_uuid, get_paysiyn, body_enc, body_dec, get_JMA, jdGsService, getSign
from crypto import aes_cbc_pk5padding, aes_cbc_pkcs7
from timer import Timer
from util import (get_current_time, json_format, sk_sign, get_date, generate_random_string,
                  get_sha256, get_hmacsha256, get_hmacsha512, get_hmacshamd5, get_sha512, get_md5, get_sha128,
                  xapieidtokenEncrypt, dict_json, get_fp43, get_eid)
from log import logger


class JD(object):
    def __init__(self):
        self.user = ''
        self.defaultAdress = ''
        self.uuid = sign_uuid()
        self.client = 'android'
        self.clientVersion = '15.0.25'
        self.sess = requests.session()
        # self.sess.mount('https://api.m.jd.com', DESAdapter())
        # self.sess.mount('http://', HTTPAdapter(max_retries=3))
        # self.sess.mount('https://', HTTPAdapter(max_retries=3))
        self.ck = ''
        self.uts = ''
        self.eid = ''
        self.area = global_config.get('config', 'area')
        self.addressid = ''
        self.lng = ''
        self.Lat = ''
        self.provinceId = ''
        self.cityId = ''
        self.districtId = ''
        self.provinceName = ''
        self.cityName = ''
        self.districtName = ''
        self.seckill_init_info = dict()
        self.seckill_url = dict()
        self.seckill_order_data = dict()
        self.send_message = global_config.getboolean('messenger', 'enable')
        self.currentOrder_response_data = dict()
        self.get_defult_addressaddressinfo = ''
        self.ui = ''
        self.address_default = dict()
        self.h5stEncryptInfo = {'b63ff': {'fp': '', 'tk': '', 'rd': '', 'enc': ''},
                                '9da72': {'fp': '', 'tk': '', 'rd': '', 'enc': ''}}  # h5st算法所需加密信息
        self.x_api_eid_token = ''
        self.userAgent = 'sprite/1.0.0;jdmall;android;version/15.0.25'  # app请求头Dalvik/2.1.0 (Linux; U; Android 7.0; VTR-TL00 Build/HUAWEIVTR-TL00)"
        self.seckillUserAgent = ''  # 秒杀请求头
        self.initLogin = False
        self.submitOrderSign = ''  # 提交订单支付签名
        self.submitPayloadBody = ''
        self.ep = ''
        self.biometricSDKToken = ''
        self.cartUUID = str(uuid.uuid4())
        self.subCartCount = 0
        self.subCartSkuList = list()
        self.jmafinger = ''
        self.jdGsService = jdGsService()
        self.jec = '',
        self.currentIp = ''

    def is_admin(self):
        try:
            # 获取当前用户的是否为管理员
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            return False

    # 获取当前ip

    def get_current_ip_address(self):
        # https://httpbin.org/ip
        response = self.sess.get("https://www.ipplus360.com/getIP")
        data = response.json()
        if isinstance(data, dict):
            ip = data['data']
        else:
            ip = data
        self.ui.console.append("{0}   当前IP地址:{1}".format(get_current_time(), ip))

    # 代理处理
    def proxy(self):
        self.sess.proxies = {}
        proxy_url = self.ui.proxy_api_address.toPlainText().replace(" ", "")
        white_list_api = self.ui.proxy_white_list.toPlainText().replace(" ", "")
        if proxy_url != '':
            self.ui.console.append("{0}   检测到当前启用代理".format(get_current_time()))
            if white_list_api != '':
                self.set_current_ip_whitelist()
            self.set_proxy_address()

    # 设置代理地址
    def set_proxy_address(self):
        proxy_url = self.ui.proxy_api_address.toPlainText().replace(" ", "")
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        }
        proxies = {
            'https': ''
        }
        resp = self.sess.get(url=proxy_url, headers=headers)
        print(resp.text)
        resp_json = json.loads(resp.text)
        if resp_json['code'] == 'SUCCESS':
            target = random.choice(resp_json['data'])
            proxies['https'] = 'http://{0}/'.format(target['server'])
            self.sess.proxies = proxies
            self.ui.console.append("{0}   成功更换代理ip地址".format(get_current_time()))
            self.get_current_ip_address()
        else:
            self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['message']))

    # 将当前ip地址加入芝麻代理白名单
    def set_current_ip_whitelist(self):
        # response = self.sess.get("https://www.ipplus360.com/getIP")
        # data = response.json()
        # ip = data['data']
        url = self.ui.proxy_white_list.toPlainText().replace(" ", "")
        url = url + self.currentIp
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        }
        resp = self.sess.get(url=url, headers=headers)
        if resp.json()['Code'] != 0:
            self.ui.console.append("{0}   {1}".format(get_current_time(), '设置代理白名单失败：' + resp.json()['Msg']))
        else:
            self.ui.console.append("{0}   {1}".format(get_current_time(), '设置代理白名单成功'))

    # 初始化ep请求参数
    def initEp(self):
        # try:
        #     self.uuid = body_dec(global_config.get('config', 'uuid'))
        # except Exception as e:
        #     self.ui.console.append("{0}   尝试读取uuid失败.请检查配置配置文件uuid参数情况。将使用随机uuid".format(get_current_time()))
        ep = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': round(time.time() * 1000),
            'ridx': -1,
            'cipher': {
                'area': body_enc(self.area),
                'd_model': 'GUnEBUPCENK=',
                'wifiBssid': 'dW5hbw93bq==',
                'osVersion': 'Dy4nBtS=',
                'd_brand': 'IPVLV0VT',
                'screen': 'CJuyCMenCNqm',
                'uuid': body_enc(self.uuid),
                'aid': body_enc(self.uuid),
                'openudid': body_enc(self.uuid)
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jingdong.app.mall'
        }
        self.ep = dict_json(ep)

    # 获取设备指纹eid
    def getEid(self):
        self.eid = get_eid(self.uuid)

    # 获取cookies的jmafringer参数
    def get_jmafinger(self):
        cookie_file_path = os.listdir('./cookies')
        if not cookie_file_path:
            self.ui.console.append("{0}   对应缓存文件不存在".format(get_current_time()))
        else:
            cookies_file = ''
            for name in os.listdir('./cookies'):
                if name.endswith('.txt'):
                    cookies_file = './cookies/{0}'.format(name)
                    break
            with open(cookies_file, 'r+', encoding='utf-8') as f:
                ck = f.readline()
                f.close()
                splitsk = ck.split(';')
                for i in splitsk:
                    item = i.split('=', 1)
                    if item[0] == 'wskey':
                        wskey = item[1]
                        self.jmafinger = get_JMA(wifi_mac='', uuid=self.uuid, eid=self.eid, wskey=wskey)

    # 构造抢购模式user-agent
    def get_seckill_userAgent(self):
        # 生成秒杀请求头
        ep = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': round(time.time() * 1000),
            'ridx': -1,
            'cipher': {
                'sv': 'CJO=',
                'ad': Cipher.encrypt(bytearray(self.uuid, 'utf-8')),
                'od': Cipher.encrypt(bytearray(self.uuid, 'utf-8')),
                'ov': 'CzK=',
                'ud': Cipher.encrypt(bytearray(self.uuid, 'utf-8'))
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jingdong.app.mall'
        }
        self.seckillUserAgent = 'jdapp;android;' + self.clientVersion + ';;;M/5.0;appBuild/100533;ef/1;ep/' + urllib.parse.quote(
            json.dumps(
                ep)) + ';jdSupportDarkMode/0;Mozilla/5.0 (Linux; Android 11; HUAWEI Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/110.0.5481.153 Mobile Safari/537.36'

    # 获取x-api-eid-token加密参数
    def get_x_api_eid_token(self):
        url = 'https://gia.jd.com/jsTk.do'
        headers = {
            'Accept': '*/*',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Host': 'gia.jd.com',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
            'Referer': 'https://marthon.jd.com/',
            'Origin': 'https://marathon.jd.com',
            'x-referer-page': 'https://marathon.jd.com/seckillM/seckill.action',
            'X-Rp-Client': 'h5_1.0.0'
        }
        a = {
            "pin": "",
            "oid": "",
            "bizId": "jx_h5_common",
            "fc": "",
            "mode": "strict",
            "p": "s",
            "fp": self.get_fp(),
            "ctype": 1,
            "v": "3.2.1.0",
            "f": "3",
            "o": "wqs.jd.com/sns/202210/20/makemoneyshop/index.html",
            "qs": "",
            "jsTk": "",
            "qi": "",
        }
        d = {
            "ts": {
                "deviceTime": round(time.time() * 1000),
                "deviceEndTime": round(time.time() * 1000)
            },
            "ca": {
                "tdHash": str(uuid.uuid4()).replace('-', ''),
                "contextName": "webgl,experimental-webgl",
                "webglversion": "WebGL 1.0 (OpenGL ES 2.0 Chromium)",
                "shadingLV": "WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)",
                "vendor": "WebKit",
                "renderer": "WebKit WebGL",
                "extensions": [
                    "ANGLE_instanced_arrays",
                    "EXT_blend_minmax",
                    "EXT_color_buffer_half_float",
                    "EXT_float_blend",
                    "EXT_texture_filter_anisotropic",
                    "WEBKIT_EXT_texture_filter_anisotropic",
                    "EXT_sRGB",
                    "OES_element_index_uint",
                    "OES_fbo_render_mipmap",
                    "OES_standard_derivatives",
                    "OES_texture_float",
                    "OES_texture_float_linear",
                    "OES_texture_half_float",
                    "OES_texture_half_float_linear",
                    "OES_vertex_array_object",
                    "WEBGL_color_buffer_float",
                    "WEBGL_compressed_texture_astc",
                    "WEBGL_compressed_texture_etc",
                    "WEBGL_compressed_texture_etc1",
                    "WEBGL_debug_renderer_info",
                    "WEBGL_debug_shaders",
                    "WEBGL_depth_texture",
                    "WEBKIT_WEBGL_depth_texture",
                    "WEBGL_lose_context",
                    "WEBKIT_WEBGL_lose_context",
                    "WEBGL_multi_draw"
                ],
                "wuv": "Qualcomm",
                "wur": "Adreno (TM) 730"
            },
            "m": {
                "compatMode": "CSS1Compat"
            },
            "fo": ["Bauhaus 93", "Casual"],
            "n": {
                "vendorSub": "",
                "productSub": "20030107",
                "vendor": "Google Inc.",
                "maxTouchPoints": 5,
                "hardwareConcurrency": 8,
                "cookieEnabled": True,
                "appCodeName": "Mozilla",
                "appName": "Netscape",
                "appVersion": "",
                "platform": "Linux aarch64",
                "product": "Gecko",
                "userAgent": "",
                "language": "zh-CN",
                "onLine": True,
                "webdriver": False,
                "javaEnabled": False,
                "deviceMemory": 8,
                "enumerationOrder": [
                    "vendorSub",
                    "productSub",
                    "vendor",
                    "maxTouchPoints",
                    "userActivation",
                    "doNotTrack",
                    "geolocation",
                    "connection",
                    "plugins",
                    "mimeTypes",
                    "webkitTemporaryStorage",
                    "webkitPersistentStorage",
                    "hardwareConcurrency",
                    "cookieEnabled",
                    "appCodeName",
                    "appName",
                    "appVersion",
                    "platform",
                    "product",
                    "userAgent",
                    "language",
                    "languages",
                    "onLine",
                    "webdriver",
                    "getBattery",
                    "getGamepads",
                    "javaEnabled",
                    "sendBeacon",
                    "vibrate",
                    "scheduling",
                    "mediaCapabilities",
                    "locks",
                    "wakeLock",
                    "usb",
                    "clipboard",
                    "credentials",
                    "keyboard",
                    "mediaDevices",
                    "storage",
                    "serviceWorker",
                    "deviceMemory",
                    "bluetooth",
                    "getUserMedia",
                    "requestMIDIAccess",
                    "requestMediaKeySystemAccess",
                    "webkitGetUserMedia",
                    "clearAppBadge",
                    "setAppBadge"
                ]
            },
            "p": [],
            "w": {
                "devicePixelRatio": 2.7500000596046448,
                "screenTop": 0,
                "screenLeft": 0
            },
            "s": {
                "availHeight": 851,
                "availWidth": 393,
                "colorDepth": 24,
                "height": 851,
                "width": 393,
                "pixelDepth": 24
            },
            "sc": {
                "ActiveBorder": "rgb(255, 255, 255)",
                "ActiveCaption": "rgb(204, 204, 204)",
                "AppWorkspace": "rgb(255, 255, 255)",
                "Background": "rgb(99, 99, 206)",
                "ButtonFace": "rgb(221, 221, 221)",
                "ButtonHighlight": "rgb(221, 221, 221)",
                "ButtonShadow": "rgb(136, 136, 136)",
                "ButtonText": "rgb(0, 0, 0)",
                "CaptionText": "rgb(0, 0, 0)",
                "GrayText": "rgb(128, 128, 128)",
                "Highlight": "rgb(181, 213, 255)",
                "HighlightText": "rgb(0, 0, 0)",
                "InactiveBorder": "rgb(255, 255, 255)",
                "InactiveCaption": "rgb(255, 255, 255)",
                "InactiveCaptionText": "rgb(127, 127, 127)",
                "InfoBackground": "rgb(251, 252, 197)",
                "InfoText": "rgb(0, 0, 0)",
                "Menu": "rgb(247, 247, 247)",
                "MenuText": "rgb(0, 0, 0)",
                "Scrollbar": "rgb(255, 255, 255)",
                "ThreeDDarkShadow": "rgb(102, 102, 102)",
                "ThreeDFace": "rgb(192, 192, 192)",
                "ThreeDHighlight": "rgb(221, 221, 221)",
                "ThreeDLightShadow": "rgb(192, 192, 192)",
                "ThreeDShadow": "rgb(136, 136, 136)",
                "Window": "rgb(255, 255, 255)",
                "WindowFrame": "rgb(204, 204, 204)",
                "WindowText": "rgb(0, 0, 0)"
            },
            "ss": {
                "cookie": True,
                "localStorage": True,
                "sessionStorage": True,
                "globalStorage": False,
                "indexedDB": True
            },
            "tz": -480,
            "lil": "",
            "wil": ""
        }
        params = {
            'a': xapieidtokenEncrypt(a)
        }
        data = {
            'd': xapieidtokenEncrypt(d)
        }
        resp = self.sess.post(url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        try:
            self.x_api_eid_token = resp_json['data']['token']
            self.sess.cookies.set('3AB9D23F7A4B3C9B', resp_json['data']['eid'])
            self.sess.cookies.set('3AB9D23F7A4B3CSS', self.x_api_eid_token)
        except:
            self.ui.console.append("{0}   获取x-api-eid-token失败!".format(get_current_time()))

    # 构建fp指纹算法参数
    def get_fp(self):
        """
                       获取浏览器指纹,根据参数去sha128加密。京东自定义了sha128加密算法。发现随机生成的也能用
                       :return:
                       """
        arr = [
            self.seckillUserAgent,
            "zh-CN",
            "applewebkit_chrome",
            "537.36",
            "linux",
            "NA",
            random.randint(1, 99),
            "851x393",
            random.randint(1, 1000),
            "sessionStorageKey",
            "localStorageKey",
            "indexedDbKey",
            "openDatabase",
            "NA",
            "Linux aarch64",
            random.randint(1, 99),
            "NA",
            "",
            "",
            "§extensions:ANGLE_instanced_arrays;EXT_blend_minmax;EXT_color_buffer_half_float;EXT_disjoint_timer_query;EXT_float_blend;EXT_frag_depth;EXT_shader_texture_lod;EXT_texture_compression_bptc;EXT_texture_compression_rgtc;EXT_texture_filter_anisotropic;EXT_sRGB;KHR_parallel_shader_compile;OES_element_index_uint;OES_fbo_render_mipmap;OES_standard_derivatives;OES_texture_float;OES_texture_float_linear;OES_texture_half_float;OES_texture_half_float_linear;OES_vertex_array_object;WEBGL_color_buffer_float;WEBGL_compressed_texture_s3tc;WEBGL_compressed_texture_s3tc_srgb;WEBGL_debug_renderer_info;WEBGL_debug_shaders;WEBGL_depth_texture;WEBGL_draw_buffers;WEBGL_lose_context;WEBGL_multi_draw§extensions:ANGLE_instanced_arrays;EXT_blend_minmax;EXT_color_buffer_half_float;EXT_disjoint_timer_query;EXT_float_blend;EXT_frag_depth;EXT_shader_texture_lod;EXT_texture_compression_bptc;EXT_texture_compression_rgtc;EXT_texture_filter_anisotropic;EXT_sRGB;KHR_parallel_shader_compile;OES_element_index_uint;OES_fbo_render_mipmap;OES_standard_derivatives;OES_texture_float;OES_texture_float_linear;OES_texture_half_float;OES_texture_half_float_linear;OES_vertex_array_object;WEBGL_color_buffer_float;WEBGL_compressed_texture_s3tc;WEBGL_compressed_texture_s3tc_srgb;WEBGL_debug_renderer_info;WEBGL_debug_shaders;WEBGL_depth_texture;WEBGL_draw_buffers;WEBGL_lose_context;WEBGL_multi_draw§w1[1, 1]§w2[1, 1024]§w38§w4yes§w58§w624§w78§w816§w932§w1016384§w111024§w1216384§w1316§w1416384§w1530§w1616§w1716§w184096§w19[32767, 32767]§w208§w21WebKit WebGL§w22WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)§w230§w24WebKit§w25WebGL 1.0 (OpenGL ES 2.0 Chromium)§wuv:Google Inc. (Intel)§wur:ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
        ]
        encryptStr = "~~~".join(str(x) for x in arr)
        return get_sha128(encryptStr)

    def setSystemTime(self):
        if self.is_admin():
            # t0 = datetime.now()
            # ret = self.get_jd_time()[2]
            # t1 = datetime.now()
            # t = float(ret) / 1000
            # dt = datetime.fromtimestamp(t) + ((t1 - t0) / 2)
            # tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(
            #     time.mktime(dt.timetuple()))
            # msec = dt.microsecond / 1000
            # win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, int(msec))
            # 向服务器发送 GET 请求，获取服务器时间戳
            jd_timestamp = int(self.get_jd_time()[2])
            # 将京东服务器时间戳转换成 UNIX 时间戳
            unix_timestamp = jd_timestamp // 1000
            # 将 UNIX 时间戳转换成 UTC 时间（精度为毫秒）
            dt = datetime.fromtimestamp(unix_timestamp, timezone.utc).replace(microsecond=jd_timestamp % 1000 * 1000)
            # 将 UTC 时间转换成本地时间
            local_dt = dt.astimezone()
            # 将本地时间调整为京东服务器时间，并设置系统时间
            if os.name == 'nt':
                # Windows 系统下调用 PowerShell 进行时间同步
                command = f'start powershell.exe -Command Set-Date "{local_dt.strftime("%d/MM/yyyy HH:mm:ss.fff")}"'
                os.system(command)
            else:
                # 其他操作系统下调用系统 API 进行时间同步
                os_time = local_dt.timestamp()
                os.system(f'sudo date --date="@{int(os_time)}"')
            return True
        else:
            return False

    # 获取京东服务器时间
    def get_jd_time(self):
        try:

            url = 'https://api.m.jd.com'
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',
            }
            t1 = int(round(time.time() * 1000))
            resp = requests.get(url=url, headers=headers)
            serverTime = int(resp.headers.get('X-API-Request-Id')[-13:])
            t2 = int(round(time.time() * 1000))
            diffTime = t2 - int(serverTime)
            need_time = t2 - t1
            return need_time, diffTime, serverTime
        except:
            self.ui.console.append("{0}   请求出错".format(get_current_time()))

    # 商品库存查询
    def get_stock(self, sku):
        url = 'https://api.m.jd.com/stocks'
        params = {
            'type': 'getstocks',
            'skuIds': sku,
            'area': self.area,
            'appid': 'item-v3',
            'functionId': 'pc_stocks'
        }
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309092b) XWEB/8555'
        }
        try:
            resp = self.sess.get(url=url, params=params, headers=headers)
            resp_json = json.loads(resp.text)
            if resp_json.get('code'):
                self.ui.console.append(
                    "{0}   检测到请求库存接口，ip被风控拦截。尝试更换代理ip".format(get_current_time()))
                self.get_x_api_eid_token()
                self.proxy()
                return False
            else:
                stockState = resp_json[sku]['StockState']
                return stockState in (33, 40, 36)
        except:
            self.ui.console.append("{0}   检测到请求库存接口，ip被风控拦截。尝试更换代理ip".format(get_current_time()))
            self.proxy()
            return False

    # 初始化app登录
    def login(self, sku, ui):
        self.ui = ui
        self.initEp()
        self.proxy()
        self.getEid()
        self.get_jmafinger()
        if self.loadCookie(ui):
            self.get_seckill_userAgent()
            self.get_x_api_eid_token()
            self.ui.userName.setText(self.user)
            self.get_defult_address(sku)
            if not isinstance(sku, str):
                for i in sku:
                    self.yuyue(sku=i)
            else:
                self.yuyue(sku=sku)
            return True
        else:
            self.ui.console.append(
                "{0}   app缓存无效或相应cookie文件缺失,请检查缓存文件情况再重新启动程序".format(get_current_time()))
            return False

    # 本地cookies转序列化
    def deserialization_cookies(self):
        cookies_file = ''
        for name in os.listdir('./cookies'):
            if name.endswith('.txt'):
                cookies_file = './cookies/{0}'.format(name)
                break
        with open(cookies_file, 'r+', encoding='utf-8') as f:
            cookies_dict = {}
            ck = f.readline()
            self.ck = ck
            f.close()
            splitsk = ck.split(';')
            for i in splitsk:
                item = i.split('=', 1)
                if item[0] == 'unionwsws':
                    unionwsws = json.loads(item[1])
                    unionwsws['devicefinger'] = self.eid
                    unionwsws['jmafinger'] = self.jmafinger
                    cookies_dict[item[0]] = json.dumps(unionwsws)
                elif item[0] == 'whwswswws':
                    cookies_dict['whwswswws'] = self.jmafinger
                else:
                    cookies_dict[item[0]] = item[1]
            # cookies = requests.utils.cookiejar_from_dict(cookies_dict, cookiejar=None, overwrite=True)
            return cookies_dict

    # 加载本地cookies
    def loadCookie(self, ui):
        self.ui = ui
        cookie_file_path = os.listdir('./cookies')
        if not cookie_file_path:
            return False
        else:
            self.sess.cookies = self.deserialization_cookies()
            if self.get_uts():
                self.initLogin = True
                return True
            else:
                return False

    def get_uts(self):
        functionId = 'newUserInfo'
        body_data = r'{"flag":"nickname","fromSource":1,"sourceLevel":1}'
        sign = getSign(functionId=functionId, body=body_data, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body_data
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
        resp_json = json.loads(resp.text)
        if resp_json.get('uts'):
            self.uts = resp_json['uts']
            self.user = resp_json['userInfoSns']['unickName']
            jec = {"hdid": "JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=", "ts": int(time.time() * 1000), "ridx": -1,
                   "cipher": {"pin": body_enc(self.user)}, "ciphertype": 5, "version": "1.2.0",
                   "appname": "com.jingdong.app.mall"}
            self.jec = quote(dict_json(jec))
            return True
        else:
            return False

    # 获取账户默认地址
    def get_defult_address(self, sku):
        functionId = 'getAddressByPin'
        body_data = r'{"isLastOrder":true,"latitude":"","longitude":"","settlementVersionCode":2540}'
        sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        data = {
            'body': body_data
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        addresslist = json.loads(resp.text)['addressList']
        for i in addresslist:
            if i['addressDefault']:
                self.lng = str(i['longitudeString'])
                self.Lat = str(i['latitudeString'])
                self.provinceId = str(i['Province'])
                self.cityId = str(i['City'])
                self.districtId = str(i['County'])
                self.provinceName = str(i['ProvinceName'])
                self.cityName = str(i['CityName'])
                self.districtName = str(i['CountryName'])
                self.user = i['Pin']
                self.addressid = str(i['Id'])
                self.defaultAdress = i['ProvinceName'] + i['CityName'] + i['CountryName'] + i['TownName']
                # addressDeatil = tripleDES_decrypt(i['Where'], 'np!u5chin@adm!n1aaaaaaa2', '00000000')
                # self.ui.address.setText(addressDeatil)
        if sku and isinstance(sku, str):
            self.address_default[sku] = json.loads(resp.text)
        else:
            self.address_default = json.loads(resp.text)

    # 账户购物车
    def cart(self):
        functionId = 'cart'
        body_data = '{"addressId":"' + self.addressid + '","appleCare":0,"businessId":"","cartBundleVersion":"15020","cartRequestType":17,"cartuuid":"' + self.cartUUID + '","configVersion":0,"degradation":0,"hitNewUIStatus":1,"homeWishListUserFlag":"2","mqTriggerStatus":"0","syntype":"1","updateTag":true,"userType":"1"}'
        sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'

        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'bef': '1',
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        cipher = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': int(round(time.time() * 1000)),
            'ridx': -1,
            'cipher': {
                'body': body_enc(body_data)
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jingdong.app.mall'
        }
        data = {
            'body': dict_json(cipher)
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        if resp_json.get('tips'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['tips']))
            return False
        if resp_json.get('cartInfo'):
            for i in resp_json['cartInfo']['vendors'] + resp_json['cartInfo']['unusableSkus'] if resp_json[
                'cartInfo'].get('unusableSkus') else resp_json['cartInfo']['vendors']:
                if i.get('sorted'):
                    for j in i['sorted']:
                        if j['item'].get('items'):
                            for k in j['item']['items']:
                                self.subCartSkuList.append({
                                    'Id': k['item']['Id'],
                                    'num': 1,
                                    'skuUuid': k['item']['skuUuid']
                                })
                        else:
                            self.subCartSkuList.append({
                                'Id': j['item']['Id'],
                                'num': 1,
                                'skuUuid': j['item']['skuUuid']
                            })
                else:
                    self.subCartSkuList.append({
                        'Id': i['Id'],
                        'num': 1,
                        'skuUuid': i['skuUuid']
                    })
        return True

    # 商品加入购物车
    def cartAdd(self, sku):
        functionId = 'cartAdd'
        body_data = '{"addressId":"' + self.addressid + '","appleCare":0,"businessId":"","businessName":"PD_addCart","cartBundleVersion":"15020","cartuuid":"' + self.cartUUID + '","configVersion":254,"coord_type":"","cvhv":"","degradation":0,"hitNewUIStatus":0,"homeWishListUserFlag":"3","isDegradeToZh":"0","latitude":"' + self.Lat + '","longitude":"' + self.lng + '","moduleVersions":{"android_cart":"15020"},"mqTriggerStatus":"0","noResponse":true,"operations":[{"TheSkus":[{"Id":"' + sku + '","num":"1"}],"carttype":"2"}],"siteId":0,"syntype":"1","userType":"1"}'
        sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'bef': '1',
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        cipher = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': int(round(time.time() * 1000)),
            'ridx': -1,
            'cipher': {
                'body': body_enc(body_data)
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jingdong.app.mall'
        }
        data = {
            'body': dict_json(cipher)
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        if resp_json.get('cartInfo'):
            self.ui.console.append("{0}   {1}加入购车成功".format(get_current_time(), sku))
        else:
            self.ui.console.append("{0}   {1}加入购车失败".format(get_current_time(), sku))

    # 账户购物车商品批量删除
    def batchDelete(self):
        if len(self.subCartSkuList) == 0:
            self.ui.console.append("{0}   当前账户购物车为空".format(get_current_time()))
            return
        functionId = 'cartRemove'
        body_data = {'addressId': '0', 'appleCare': 0, 'businessId': '', 'cartBundleVersion': '15020',
                     'cartuuid': self.cartUUID, 'configVersion': 249, 'coord_type': '',
                     'cvhv': '', 'degradation': 0, 'hitNewUIStatus': 1, 'homeWishListUserFlag': '2',
                     'latitude': '', 'longitude': '', 'mqTriggerStatus': '0',
                     'operations': [{'TheSkus': self.subCartSkuList,
                                     'carttype': '4'}],
                     'syntype': '1', 'updateTag': False, 'userType': '1'}
        body_data = dict_json(body_data)
        sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'bef': '1',
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        cipher = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': int(round(time.time() * 1000)),
            'ridx': -1,
            'cipher': {
                'body': body_enc(body_data)
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jingdong.app.mall'
        }
        data = {
            'body': dict_json(cipher)
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)

    # 账户购物车全选操作
    def cartCheckAll(self):
        self.ui.console.append("{0}   正在购物选取全选操作".format(get_current_time()))
        self.subCartCount = 0
        functionId = 'cartCheckAll'
        body_data = '{"addressId":"' + self.addressid + '","appleCare":0,"businessId":"","cartBundleVersion":"15020","cartuuid":"' + self.cartUUID + '","configVersion":249,"coord_type":"","degradation":0,"hitNewUIStatus":1,"homeWishListUserFlag":"2","latitude":"' + self.Lat + '","longitude":"' + self.lng + '","mqTriggerStatus":"0","operations":[{"carttype":"7"}],"syntype":"1","updateTag":false,"userType":"1"}'
        sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'bef': '1',
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        cipher = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': int(round(time.time() * 1000)),
            'ridx': -1,
            'cipher': {
                'body': body_enc(body_data)
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jingdong.app.mall'
        }
        data = {
            'body': dict_json(cipher)
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        if resp_json.get('cartInfo'):
            for i in resp_json['cartInfo']['vendors']:
                for j in i['sorted']:
                    if j['item']['isNoCheck'] == 1:
                        self.ui.console.append(
                            "{0}   检测到当前商品不可勾选:{1}".format(get_current_time(), j['item']['Name']))
                    else:
                        self.subCartCount += 1
                    # if j['item'].get('items'):
                    #     for k in j['item']['items']:
                    #         if k['item']['isNoCheck'] == 1:
                    #             self.ui.console.append(
                    #                 "{0}   检测到当前商品不可勾选:{1}".format(get_current_time(), k['item']['Name']))
                    #         else:
                    #             self.subCartCount += 1
                    # else:
                    #     if j['item']['isNoCheck'] == 1:
                    #         self.ui.console.append(
                    #             "{0}   检测到当前商品不可勾选:{1}".format(get_current_time(), j['item']['Name']))
                    #     else:
                    #         self.subCartCount += 1
            if self.subCartCount < 1:
                self.ui.console.append("{0}   检测到账户当前购物车可勾选商品数量少于1".format(get_current_time()))
                return False
            else:
                return True

    # 商品预约
    def yuyue(self, sku):
        functionId = 'appoint'
        body_data = r'{"autoAddCart":"0","bsid":"","check":"0","ctext":"","isShowCode":"0","mad":"0","skuId":"' + sku + '","type":""}'
        sign = getSign(functionId=functionId, body=body_data, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body_data
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
        resp_json = json.loads(resp.text)
        if resp_json['isSuccess']:
            self.ui.console.append("{0}   预约成功:{1}".format(get_current_time(), resp_json['title']))
        else:
            self.ui.console.append("{0}   预约失败:{1}".format(get_current_time(), resp_json['title']))

    # aes加密
    def aes_encrypt(self, body, key):
        return aes_cbc_pkcs7.encrypt(text=body, key=key)

    # 获取h5st算法的token,加密算法，rd
    def get_h5st_token(self, ai, headers, payload):
        url = 'https://cactus.jd.com/request_algo?g_ty=ajax'
        resp = self.sess.post(url=url, headers=headers, json=payload)
        result = json.loads(resp.text)
        if result['status'] == 200:
            self.h5stEncryptInfo[ai]['tk'] = result['data']['result']['tk']
            algo = result['data']['result']['algo']
            self.h5stEncryptInfo[ai]['rd'] = re.search(r'rd=\'(.*?)\'', algo).group(1)
            self.h5stEncryptInfo[ai]['enc'] = re.search(r'return algo\.(.*?)\(', algo).group(1)

    # 生成h5st算法第五段参数的动态加密key
    def get_h5st_signStr_key(self, ai, enctry_str):
        encrypt = self.h5stEncryptInfo[ai]['enc']
        tk = self.h5stEncryptInfo[ai]['tk']
        key = ''
        if encrypt == 'HmacSHA256':
            key = get_hmacsha256(tk, enctry_str)
        if encrypt == 'HmacSHA512':
            key = get_hmacsha512(tk, enctry_str)
        if encrypt == 'HmacMD5':
            key = get_hmacshamd5(tk, enctry_str)
        if encrypt == 'SHA256':
            key = get_sha256(enctry_str)
        if encrypt == 'SHA512':
            key = get_sha512(enctry_str)
        if encrypt == 'MD5':
            key = get_md5(enctry_str)
        return key

    # 利用这一步将app端cookies转为m端cookies
    def getToken(self, url):
        functionId = 'genToken'
        body_data = r'{"action":"to","to":"' + url + '"}'
        sign = getSign(functionId=functionId, body=body_data, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body_data
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
        return json.loads(resp.text)['tokenKey'], json.loads(resp.text)['url']

    # 账户uts

    # 构建提交订单所需body数据
    def currenrOrder_data(self, sku, Num):
        address_data = self.address_default[sku]
        OrderStr = dict()
        num = len(address_data['addressList'])
        try:
            for i in address_data['addressList']:
                if i['addressDefault']:
                    OrderStr['CoordType'] = i['CoordType']
                    OrderStr['Id'] = i['Id']
                    OrderStr['IdArea'] = i['IdArea']
                    OrderStr['IdCity'] = i['IdCity']
                    OrderStr['IdProvince'] = i['IdProvince']
                    OrderStr['IdTown'] = i['IdTown']
                    OrderStr['Latitude'] = i['Latitude']
                    OrderStr['Longitude'] = i['Longitude']
                    OrderStr['Mobile'] = i['MobileReal']
                    OrderStr['Name'] = i['Name']
                    OrderStr['Where'] = i['Where']
                    OrderStr['addressDefault'] = i['addressDefault']
                    OrderStr['addressDetail'] = i['addressDetail']
                    OrderStr['addressUUID'] = i['addressUUID']
                    OrderStr['areaCode'] = i['areaCode']
                    OrderStr['closedTimeStampForRecommend'] = ''
                    OrderStr['closedVersion'] = ''
                    OrderStr['globalCacheAddressTitle'] = i['addressDetail']
                    OrderStr['isNeedVirtualData'] = True
                    OrderStr['isOpenPaymentPassword'] = True
                    OrderStr['isPresentAddress'] = True
                    OrderStr['isShortPwd'] = False
                    OrderStr['latitudeDefault'] = self.Lat
                    OrderStr['latitudeString'] = self.Lat
                    OrderStr['longitudeDefault'] = self.lng
                    OrderStr['longitudeString'] = self.lng
                    OrderStr['plusExposureCount'] = 0
                    OrderStr['plusFloorClosedTimeStamp'] = ''
                    OrderStr['plusJdkClosedTimeStamp'] = ''
                    OrderStr['redpacket_channel'] = 'JD'
                    OrderStr['retainTipsNumber'] = 0
                    OrderStr['userPrivacyFirstVisit'] = True
        except Exception:
            self.ui.console.append("{0}   获取地址信息出现异常").format(get_current_time())
        data = {
            'CartStr': {
                'TheSkus': [
                    {
                        'Id': sku,
                        'num': Num
                    }
                ]},
            'OrderStr': OrderStr,
            'addressGlobal': True,
            'addressTotalNum': num,
            'allCheckedBuyLicenseIds': '',
            'appEID': self.eid,
            'cartAdd': {
                'atmosphereList': [],
                'extFlag': {},
                'wareId': sku,
                'wareNum': Num
            },
            'decryptType': '2',
            'giftType': 0,
            'hasDefaultAddress': True,
            'hasSelectedOTC': '0',
            'isLastOrder': True,
            'isRefreshOrder': False,
            'isSupportAllInvoice': True,
            'operationType': 0,
            'otcMergeSwitch': '1',
            'sdkToken': self.x_api_eid_token,
            'settlementVersionCode': 2540,
            'skuSource': 0,
            'sourceType': 2,
            'supportAllEncode': True,
            'supportNewParamEncode': True,
            'wareId': sku,
            'wareNum': Num

        }
        return data

    # 构建提交订单所需body数据(多商品)
    def currenrOrder_data_skupack(self):
        address_data = self.address_default
        OrderStr = dict()
        num = len(address_data['addressList'])
        try:
            for i in address_data['addressList']:
                if i['addressDefault']:
                    OrderStr['CoordType'] = i['CoordType']
                    OrderStr['Id'] = i['Id']
                    OrderStr['IdArea'] = i['IdArea']
                    OrderStr['IdCity'] = i['IdCity']
                    OrderStr['IdProvince'] = i['IdProvince']
                    OrderStr['IdTown'] = i['IdTown']
                    OrderStr['Latitude'] = i['Latitude']
                    OrderStr['Longitude'] = i['Longitude']
                    OrderStr['Mobile'] = i['MobileReal']
                    OrderStr['Name'] = i['Name']
                    OrderStr['Where'] = i['Where']
                    OrderStr['addressDefault'] = i['addressDefault']
                    OrderStr['addressDetail'] = i['addressDetail']
                    OrderStr['addressUUID'] = i['addressUUID']
                    OrderStr['areaCode'] = i['areaCode']
                    OrderStr['closedTimeStampForRecommend'] = ''
                    OrderStr['closedVersion'] = ''
                    OrderStr['globalCacheAddressTitle'] = i['addressDetail']
                    OrderStr['isNeedVirtualData'] = True
                    OrderStr['isOpenPaymentPassword'] = True
                    OrderStr['isPresentAddress'] = True
                    OrderStr['isShortPwd'] = False
                    OrderStr['latitudeDefault'] = self.Lat
                    OrderStr['latitudeString'] = self.Lat
                    OrderStr['longitudeDefault'] = self.lng
                    OrderStr['longitudeString'] = self.lng
                    OrderStr['plusExposureCount'] = 0
                    OrderStr['plusFloorClosedTimeStamp'] = ''
                    OrderStr['plusJdkClosedTimeStamp'] = ''
                    # OrderStr['postCode'] = i['postCode']
                    OrderStr['redpacket_channel'] = 'JD'
                    OrderStr['retainTipsNumber'] = 0
                    OrderStr['userPrivacyFirstVisit'] = True
        except Exception:
            self.ui.console.append("{0}   获取地址信息出现异常").format(get_current_time())
        data = {
            'CartStr': {},
            'OrderStr': OrderStr,
            'addressGlobal': True,
            'addressTotalNum': num,
            'allCheckedBuyLicenseIds': '',
            'appEID': self.eid,
            'decryptType': '2',
            'giftType': 0,
            'hasDefaultAddress': True,
            'hasSelectedOTC': '0',
            'isLastOrder': True,
            'isRefreshOrder': False,
            'isSupportAllInvoice': True,
            'operationType': 0,
            'otcMergeSwitch': '1',
            'sdkToken': self.x_api_eid_token,
            'settlementVersionCode': 1800,
            'skuSource': 0,
            'sourceType': 1,
            'supportAllEncode': True,
            'supportNewParamEncode': True
        }
        return data

    # 构建提交订单所需body数据（定金预售模式）
    def currenrOrder_data_deposit(self, sku):
        """
        定金预售
        :param sku:
        :return:
        """
        address_data = self.address_default[sku]
        OrderStr = dict()
        num = len(address_data['addressList'])
        for i in address_data['addressList']:
            if i['addressDefault']:
                OrderStr['CoordType'] = i['CoordType']
                OrderStr['Id'] = i['Id']
                OrderStr['IdArea'] = i['IdArea']
                OrderStr['IdCity'] = i['IdCity']
                OrderStr['IdProvince'] = i['IdProvince']
                OrderStr['IdTown'] = i['IdTown']
                OrderStr['Latitude'] = i['Latitude']
                OrderStr['Longitude'] = i['Longitude']
                OrderStr['Mobile'] = i['MobileReal']
                OrderStr['Name'] = i['Name']
                OrderStr['Where'] = i['Where']
                OrderStr['addressDefault'] = i['addressDefault']
                OrderStr['addressDetail'] = i['addressDetail']
                OrderStr['addressUUID'] = i['addressUUID']
                OrderStr['areaCode'] = i['areaCode']
                OrderStr['closedTimeStampForRecommend'] = ''
                OrderStr['closedVersion'] = ''
                OrderStr['globalCacheAddressTitle'] = i['addressDetail']
                OrderStr['isNeedVirtualData'] = True
                OrderStr['isOpenPaymentPassword'] = True
                OrderStr['isPresentAddress'] = True
                OrderStr['isShortPwd'] = False
                OrderStr['latitudeDefault'] = self.Lat
                OrderStr['latitudeString'] = self.Lat
                OrderStr['longitudeDefault'] = self.lng
                OrderStr['longitudeString'] = self.lng
                OrderStr['plusExposureCount'] = 0
                OrderStr['plusFloorClosedTimeStamp'] = ''
                OrderStr['plusJdkClosedTimeStamp'] = ''
                OrderStr['postCode'] = i['postCode']
                OrderStr['redpacket_channel'] = 'JD'
                OrderStr['retainTipsNumber'] = 0
                OrderStr['userPrivacyFirstVisit'] = True

        data = {
            'CartStr': {
                'TheSkus': [
                    {
                        'Id': sku,
                        'num': '1'
                    }
                ]},
            'OrderStr': OrderStr,
            'addressGlobal': True,
            'addressTotalNum': num,
            'appEID': self.eid,
            'cartAdd': {
                'extFlag': {},
                'wareId': sku,
                'wareNum': '1'
            },
            'decryptType': '2',
            'giftType': 0,
            'hasDefaultAddress': True,
            'hasSelectedOTC': '0',
            'isLastOrder': True,
            'isPresale': True,
            'isRefreshOrder': False,
            'isSupportAllInvoice': True,
            'operationType': 0,
            'otcMergeSwitch': '1',
            'sdkToken': self.x_api_eid_token,
            'settlementVersionCode': 2540,
            'skuSource': 4,
            'sourceType': 2,
            'supportAllEncode': True,
            'supportNewParamEncode': True,
            'wareId': sku,
            'wareNum': '1'

        }
        return data

    # 获取订单信息
    def currentOrder(self, sku, num):
        # 进入结算页(加车模式)
        functionId = 'currentOrder'
        body_data = dict_json(self.currenrOrder_data(sku=sku, Num=num))
        sign = getSign(functionId=functionId, body=body_data, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        data = {
            'body': body_data
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        if resp_json.get('code') and resp_json['code'] == '605':
            self.ui.console.append('{0}   {1}'.format(get_current_time(), '验证一下，购物无忧'))
            return False
        if resp_json.get('tips'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['tips']))
            return False
        if not resp_json.get('lastOderInfo'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['exceptionMsg']))
            return False
        self.currentOrder_response_data[sku] = json.loads(resp.text)
        self.submit_data(sku=sku, num=num)
        return resp.text

    # 获取订单数据（多商品）
    def currentOrderSkuPack(self):
        # 进入结算页(购物车模式)
        functionId = 'currentOrder'
        body_data = dict_json(self.currenrOrder_data_skupack())
        sign = getSign(functionId=functionId, body=body_data, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        data = {
            'body': body_data,
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        if resp_json.get('tips'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['tips']))
            return False
        if not resp_json.get('lastOderInfo'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['exceptionMsg']))
            return False
        self.currentOrder_response_data = json.loads(resp.text)
        self.submit_data_skupack()
        return resp.text

    # 获取订单数据(定金模式)
    def currentOrder_deposit(self, sku):
        # 进入结算页(定金模式)
        functionId = 'currentOrder'
        body_data = json.dumps(self.currenrOrder_data_deposit(sku=sku))
        sign = getSign(functionId=functionId, body=body_data, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        data = {
            'body': body_data
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body_data)
        resp = self.sess.post(url=url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        if resp_json.get('tips'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['tips']))
            return False
        if not resp_json.get('lastOderInfo'):
            self.ui.console.append('{0}   {1}'.format(get_current_time(), resp_json['exceptionMsg']))
            return False
        self.currentOrder_response_data[sku] = resp_json
        self.submit_data_deposit(sku=sku)
        return resp.text

    def get_biometricSDKToken(self):
        url = 'https://jrtdcert.jd.com/vttok.json.json'
        headers = {
            'Host': 'jrtdcert.jd.com',
            'User-Agent': self.userAgent,
            'Content-Type': 'application/json;charset=utf-8',
            'Accept': 'application/json'
        }
        payload = "{\"data\": \"AKS*_*MIIEhQYJKoZIhvcNAQcDoIIEdjCCBHICAQAxggGSMIIBjgIBADB2MF4xGDAWBgNVBAMMD1dhbmdZaW4gVXNlciBDQTEfMB0GA1UECwwWV2FuZ1lpbiBTZWN1cml0eUNlbnRlcjEUMBIGA1UECgwLV2FuZ1lpbi5jb20xCzAJBgNVBAYTAkNOAhRv1qEBtyng9uYoK4ZGz4ZoGs8wGDANBgkqhkiG9w0BAQEFAASCAQC4MAmZq7xxPgm3ZaQ+i2bsDk2c3oHnvYlvMuiDDf7N+d7FWFCJ1O4QTZtnX\\/58+uK3bMhvqWquAXE8ufJPvKeaVMNezGD7SfboiZijeB9nZY6ugaBO6jA7T3E6DVOwFRV9DSb06e249RREnbWI8NSM4Or3Pyg5kEhAIRdBogYR+ZToFrxg1xPFF4eimM+EBrajOWbIW1CexAPsSgQU5z33cSbKYugcgzn4srxM1C1kLWE7twjN4EIAg3yniQq\\/aTHNIGhzwGUk\\/VyUGNidPquyM0QAx7KHhaxtJtDPHFvhNd7X0YsmxywyU0C45sfPgUk1BUxB2RtbqfqpFH+vNuSeMIIC1QYJKoZIhvcNAQcBMBQGCCqGSIb3DQMHBAgqhkiG9w0DB4CCArA+\\/kuMTgM6mK78iD\\/pG14lHhM0M0ptqHUh4LR9GOQbDj+I9cqXnA46GZOzlK11oBZCEX9TmkbnkecPcGIiT9BdsnD9\\/oqFC+01YPnI3n4nYk\\/NYVKX5FNngDOQfe7803by8BRVjwcTJAqE4cGuh7a0K5sHUDPDUqsPnwBw6NUxziXaXgEhJpmXt+VnrrPAAR5MKLA+\\/fA8YoVAIzlzQ2qggP4y+W9hB2UP19qtk5SBCYoNCsG794VEvauBkXvHOLAcuI3UTbj7vSZL7bGLjP\\/G+y3xEPk8TBSKaHhMsWOFRhESCdRffPRmIfhqAtP0GGATQ0SqVPPFBXS2OVVmhczcLB8YbBHEzjlVmaRN023rY9U7dJ4hrBLhW\\/V78nT1RczzAXzJcKvI2mEQwkgFaJSYQ0qiqmBAuJDdzgK86dO+ANhRpMhhb+qqEtWz5a4EyDlsOXtkjMMIIVvUxZUg3qAxZh8VF2dmZ67mghZnUe+pEBDt4KHxFS5kXP2\\/JajW43WM+rUG5lNgjVeqIx1+I5kYi7KEYytxT7HjGPz3ifRGWI4Fi3hgk7kVyGrmLeWXz1MutEFmZlvrbJsARpx\\/wusswnAibd2+YKd+NsxNpZZtt5HcPVOlZRqvznnI+g15dAxspkq9aC8rpWrDJDnVeG\\/UjS3+WPapHtAOnI+20pu1IirO8Yz7ppVaUeRdO2TGuBgq3j9FrE6BMMwUiBf8K4MewDFoosxg0zHlsEfO8g7DESr9dHjLnhvLnqqZDnEOc1x8RLTvfeN4IcOd4eq3tg8uqGLd44\\/\\/lnXx4L7qK6eKXhA83V9MvGqPI7ovorJC4daKFlD+eNjpUoG4KjlRs3C3e5SnE54A3WwyPVO90XmRDpqMV7AJFtBwlA6ROrkfoclcmtOw9SgBhGoa7Ga63mQ+\",\"visaType\": \"1\",\"visa\": \"\",\"aks\": \"1\"}"
        resp = self.sess.post(url=url, headers=headers, data=payload)
        # data = r'{"data":"AKS*_*MIILDQYJKoZIhvcNAQcDoIIK\/jCCCvoCAQAxggGSMIIBjgIBADB2MF4xGDAWBgNVBAMMD1dhbmdZaW4gVXNlciBDQTEfMB0GA1UECwwWV2FuZ1lpbiBTZWN1cml0eUNlbnRlcjEUMBIGA1UECgwLV2FuZ1lpbi5jb20xCzAJBgNVBAYTAkNOAhRv1qEBtyng9uYoK4ZGz4ZoGs8wGDANBgkqhkiG9w0BAQEFAASCAQC2wM1jvmlM3Xk5ZGA\/yywvKV71SIluSpBsD90gSFeZ8RP0y8ychOE\/CteAcRdHfWsFDEGbBIrwQ+q4I6hOA2zEl4P\/GJ86HwNMR4XD4C1VipolFtINHzlPeqmalfNBw5JGaAoHu6wW7dfZHiGK+\/jUgUhh1JO\/i\/5AIeunHiiK8RE+VEMXMloyS9XAWBxhtqbrioo802840icfSnwIS1U03YVV4X7rDTyhTIkzxc4cHCcz\/pnQoi\/8HTzbiXEfvPFLEvc3jInzzQ1CmMcOHZne6mPtCgt2lzj4BPVCkHIfTfaXbQGpepOr1NtR190iTbRBBMhUpKEAqf5D29gMget6MIIJXQYJKoZIhvcNAQcBMBQGCCqGSIb3DQMHBAgqhkiG9w0DB4CCCThnlkbxDwqi4xXxXd8xzbib427s3SitLvDue\/h+cFPzXYQeNc72jfLSMCB7eCdIIiG980vNvyEjyNSHjWQbjTCjkG+Gx3aS4qrFcWQNRISwq+rWmmbm5TZzetcJTA6MQPOqa+++5t1uYDwwjwUXarLdUBNnV3AB5hTW9kVkK9lYaY6JlW1W1GQyVpplh2lBCcFsXgQ4vSrkxYm\/WEnTdjuCvl3uVD8\/eWTYCPZ8TqqC8PauzjZTh5wsYpNnWrGUtn8EtELE7ca5vFyuyy0J3bJRfHnJxU69XCI6GSeSE9VqNDa1\/16N99z3TuODbb2az7RR\/9WY2JCeqAGAJQjEgWbGW9eC\/nxrPrj5wxpfK6\/gOwNevy4Qwqe+GbAQkwyI8GYu+2vYhD4hQLJDwVscBdFaPRuJKQ\/0JFQtO0V1NKkxcR4eNky+pRIAXKIGimYIfxwqjPHXPWj5slyv+H8jTjnqVHhhiMO0s1b\/AGiktxcBQfZ32rkj7AGVJ\/O8f1T9bp7O+DxoVJ5SBA0IxDyHSMcFB650FifQOqvqT06WQW+4KNB6nWxgiZIvJG+hgto5kwYT8HfwYh+O+HceeP+WLtslrG5PqceRtOEr0xCwG5NzWTvX9g4mGSmxYA46tzNelPoMz5fo5ZtV19Zorb85eYxI0wKpDpsDhtOuap1FWCWO8huz9VjPi4jjjbVoynUWxWRsEPXmZK+coosZu6JsQ92WCflvj1ofwq\/AvbVVUScsFPYXVWwYAlKZpGuGXw54XRf6fIZa4ysgVlyjOKUSXH\/5cpLdy5RIKokQjXemUvfAG4WLNufyo9rrP7xDRJbRuJV8Igj0W7lzdXvi9LuALd7HhzIqz8WB0YxtaLkTsere1RcqJ71I2A97\/SkuyQ872cNof7GJfOkVWRKvd8Iv6TZsuiXrYJ043X6C5M\/ZISKAxTlbfQCuTUJ5Ivblob56QqRAWDyE79NYDc10Iapdz71acC6ISq7UFMmSvGvDNrETlmtiIHjGsP\/palqZpHzBQqzOMsPISn6MgACr+2hgbKXMxQGLnkt\/jEGHk3VOr+Fgv7TfQbxrOdSGi2KEQBSwdP+Q6KfUw2ElAGhnwMqAAecqR9\/XW5ZVTAVxnYJql3e3fYJ2tAyjPaioLcJdEqHla7kyASmzgJemFRxlo4ycJCKdM\/cYjXyUPBM0ouLOTC7O+Nl47uNsmDJwyiECmVwKMfkvj4xZyBkk6Yi2pl0j566iARpYnVHCSv4qdXLxPoQl75Gs3A6BnDxG+VMyWYQPLq7h107UFnO9ULJvn\/Uh+tZ6EwZfvLrhBcCSGP\/yY374qHc7Ri0Omuk1AopZl\/TDmwiOpKFs54WuVlbG5jcZVtKPVKIOMV3hJ40l78rKQ3lQTo4Ej7LczMReyixsWsll28bbKcuJ5TAbXpw7pkjvdL4eJik23+EKHXDcoziwtDcQ5y\/VJEGczrQ68Y++yLcpmAEjDCezvWrEu\/MHBDBnHpOcExZOMxs6\/0OYjjEirPL9P+DBnV\/uIa8N9uMKhGTiDd8CNPixKFvu4B4bP4YP3yRKUz\/TV+iaj9dnH9Gc1V9K\/y7mokeCjX1W4K\/7MnNXBgCkTvHf7I1\/FutvWkYrw+Hc7+5fd6Lf1NOVA3SI1Ay4pAx9rHGV5X0ZwZPsh59JjBP174553+zOFkiXHWhJGzofLLai4pAwy+RXq4jPn4qn3DlY2HP5qSy6RVTxL15nV6g\/M1Kee5McC3Gmecj8RtQPsPJcjC4ZqPwzRmnJ7h29K8wRu\/t1AAAdyc+N\/inxurC70nkcgBaCPH5U3VMnw1I4pHo80EcyyDK7063eocQu6VdBC5fi+yR\/YsfHIVYNvBcEO8OiSYpnNgw4ElQLQym2XofxnkSx8mBu4Qu2nRSJnyhd+d+JslcTBUkXsLXauzXqMxFKNgBkCgM6Kjeiiyd2\/gU4mt\/e81LttebpXhNaBkrGRXCN4J5qP9HE5TGpGwF3wCSpMZU+B15LK1kWwmhHgQzzq5CFtaBm\/8oNYuBOEza1hqwZ1VUf0TCbQ7s07ehxMHFjeK0vErGMgYGa+5IsuikirPNxoQj3uAY1rr9HAKkZc4YM9qHe2hc2MkWaRiZone87VTtZNO6GPcE22Qiq0KKe3aX4FqRGv9Oi+tjHK5UdHilf0M2vk76e8S9+kWNSwcy5+ghlxuyoDgBIEiB1XUZulSpVdCmLw5YUbP6m3q1m0fkyoqmVa3AnnLsRLZcOSXLOIuUszQ7j6nJkN5\/QbJOquSxhGobWpokw+5oExYFS0FHs5KefT7AGyAmrHDQ9JIu5otxUlgXJBB2UBvm3rQxLX8JEbfGI7i3iWmBC7yq917wxhl2ln6k3dyiNXC2iWNTceFjywdW7HOT+n0lks1B4unX8Z8k42nVk3C6bGuOnuCeODzDJfXeS6jALTJkHPQNbuQHPdfVNbjr0hG5dNUMGHC206PHdXzP7jqaPG\/LlxTUG0mGNMEPlZr4ea5bOEFWTphKsJRds6q9YqstPRVCX9j2q9GLGv43vaSIU+kqtJLs4SwEHeli2n7JPmYu6a5lJSC0ud8K7lwT2ILVnxxhsQIVIyGaYtWUiVu7qWhbUm1gyh5oxC7FsThZbwA4GLKZb1qpE5lbjNEC3AK8PGnGA+GwUu9F8ZcAYzRdHuShr1\/Uoi8frr2lAH5B8nsHnQ49l6H69Wrjd+d7Q+zii0IDfsG0L5w+gn4hghHgrrd2T+3+owZQI83kwvNmyP2mBduEnfR09E1fJ1wEeIfWU4QSAk0Hu3xm+eJG1dIfPnu75WdSH263PWrAD++qBqaj34N7FndfSMR05fcXIUQvebI5sdHgVF\/Nn8Pdh48AWJjg+1BFU5cjNEr6lVAfQ6SvD2npTbjb4Ho6mp\/\/gVW9Osg8sCXzqrPpqd\/aq2HGKcH7b34YgBg9y1FMaUDIiSFXFZgxPXMDnS7VZb\/l3x5Vjq15np0btUUjincnqu3jZwxMICVS9lun03vcpTDKobuV5kUGdhk+6FAAH7jN6g9\/jz\/mBLpYtbSITvMoufKADuFGzgppXoD272kqaEkMtwlw6GYG729j7HwmnspH5P\/jQSiKUp23ez1i8M0eWky\/T0wgnnbJUhEYy6bBDmEaKfj8ICz8ecuXr\/g==","visaType":"1","visa":"","aks":"1"}'
        self.biometricSDKToken = json.loads(resp.text)['data']['token']

    # 构建生成订单所需body数据
    def submit_data(self, sku, num):
        OrderStr = dict()
        orderUnion = dict()
        try:
            OrderStr['Id'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['Id']
            OrderStr['IdArea'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdArea']
            OrderStr['IdCity'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdCity']
            OrderStr['IdProvince'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdProvince']
            OrderStr['IdTown'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdTown']
            OrderStr['Mobile'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['MobileReal']
            OrderStr['Name'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['Name']
            OrderStr['Where'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['Where']
            OrderStr['addressDetail'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['addressDetail']
            OrderStr[
                'aiRiskOrderEmbeddig'] = '0|22|A00|Kb2|C0y|KCR|CJτ|Ccs|MόI|MDϏ|C2u|Bνη|MBϒ|Cσt|Crβ|MBν|MUp|Bϕd|C7ς|10|00|0|O|σ|p'
            OrderStr['inputPasswordExplain'] = '请输入6位数字密码'
            OrderStr['isDjGlobalAddressCharge'] = False
            OrderStr['isFriendPayForMeSubmit'] = False
            OrderStr['isIdCardVerifyRequired'] = False
            OrderStr['isLimitBuyVender'] = False
            OrderStr['isNeedVirtualData'] = True
            OrderStr['isNotChoseConsolidatorShop'] = False
            OrderStr['isOpenPaymentPassword'] = True
            OrderStr['isPayForMeSubmit'] = False
            OrderStr['isShortPwd'] = True
            OrderStr['latitudeDefault'] = self.currentOrder_response_data[sku]['lastOderInfo']['address'][
                'latitudeString']
            OrderStr['latitudeString'] = self.currentOrder_response_data[sku]['lastOderInfo']['address'][
                'latitudeString']
            OrderStr['longitudeDefault'] = self.currentOrder_response_data[sku]['lastOderInfo']['address'][
                'longitudeString']
            OrderStr['longitudeString'] = self.currentOrder_response_data[sku]['lastOderInfo']['address'][
                'longitudeString']
            OrderStr['orvp'] = ''  # 这个参数暂时不知怎么来
            OrderStr['plusExposureCount'] = 2,
            OrderStr['plusFloorClosedTimeStamp'] = ''
            OrderStr['plusJdkClosedTimeStamp'] = ''
            OrderStr['rechargeList'] = []
            OrderStr['retainTipsNumber'] = 0
            OrderStr['redpacket_channel'] = 'JD'
            OrderStr['submitTransferJson'] = self.currentOrder_response_data[sku]['lastOderInfo']['submitTransferJson']
            OrderStr['time'] = int(time.time() * 1000)
            OrderStr['venderRemarkList'] = []
            # orderUnion['advertise_app'] = ''
            # orderUnion['appkey'] = '1b41a7042ce724d9ecaa5a15fe9fab7a'
            # orderUnion['channel_id'] = 'wandoujia'
            # orderUnion['fe_order_track'] = ''
            # orderUnion['union_id'] = '50966'
            # orderUnion['uuid'] = self.uuid
            data = {
                'AppKeplerParams': {'otherData': {'mopenbp5': ''}},
                'CartStr': {'TheSkus': [{'Id': sku, 'num': num}]},
                'OrderStr': OrderStr,
                'SupportJdBean': True,
                'appEID': self.eid,
                'biometricSDKToken': self.x_api_eid_token,
                'cartuuid': str(uuid.uuid4()),
                'decryptType': '2',
                'fk_appId': 'com.jingdong.app.mall',
                'fk_latitude': self.Lat,
                'fk_longtitude': self.lng,
                'fk_terminalType': '02',
                'fk_traceIp': '10.1.10.1',
                'jdvTime': str(int(time.time()) * 1000),
                # 'm_param': '',
                # 'm_paramTime': str(int(time.time()) * 1000),
                'orderUnion': {},
                # 'se': '',
                'settlementVersionCode': 2540,
                # 'si': '',
                'supportAllEncode': True,
                'supportNewParamEncode': True,
                'syntype': '1',
                'unpl': '',
                'transferJson': self.currentOrder_response_data[sku]['lastOderInfo']['transferJson'],

            }
            body = dict_json(data)
            self.submitOrderSign = getSign(functionId='submitOrder', body=body, client='android',
                                           clientVersion=self.clientVersion, uuid=self.uuid)
            self.submitPayloadBody = body
        except Exception as e:
            self.ui.console.append("{0}   结算哥哥偷懒...请求订单结算数据失败.请更换ip重试".format(get_current_time()))
            return

    # 构建生成订单所需body数据(多商品)
    def submit_data_skupack(self):
        OrderStr = dict()
        try:
            OrderStr['Id'] = self.currentOrder_response_data['lastOderInfo']['address']['Id']
            OrderStr['IdArea'] = self.currentOrder_response_data['lastOderInfo']['address']['IdArea']
            OrderStr['IdCity'] = self.currentOrder_response_data['lastOderInfo']['address']['IdCity']
            OrderStr['IdProvince'] = self.currentOrder_response_data['lastOderInfo']['address']['IdProvince']
            OrderStr['IdTown'] = self.currentOrder_response_data['lastOderInfo']['address']['IdTown']
            OrderStr['Mobile'] = self.currentOrder_response_data['lastOderInfo']['address']['MobileReal']
            OrderStr['Name'] = self.currentOrder_response_data['lastOderInfo']['address']['Name']
            OrderStr['Where'] = self.currentOrder_response_data['lastOderInfo']['address']['Where']
            OrderStr['addressDetail'] = self.currentOrder_response_data['lastOderInfo']['address']['addressDetail']
            OrderStr[
                'aiRiskOrderEmbeddig'] = '0|22|A00|Kb2|C0y|KCR|CJτ|Ccs|MόI|MDϏ|C2u|Bνη|MBϒ|Cσt|Crβ|MBν|MUp|Bϕd|C7ς|10|00|0|O|σ|p'
            OrderStr['inputPasswordExplain'] = '请输入6位数字密码'
            OrderStr['isDjGlobalAddressCharge'] = False
            OrderStr['isFriendPayForMeSubmit'] = False
            OrderStr['isIdCardVerifyRequired'] = False
            OrderStr['isLimitBuyVender'] = False
            OrderStr['isNeedVirtualData'] = True
            OrderStr['isNotChoseConsolidatorShop'] = False
            OrderStr['isOpenPaymentPassword'] = True
            OrderStr['isPayForMeSubmit'] = False
            OrderStr['isShortPwd'] = True
            OrderStr['latitudeDefault'] = self.currentOrder_response_data['lastOderInfo']['address'][
                'latitudeString']
            OrderStr['latitudeString'] = self.currentOrder_response_data['lastOderInfo']['address'][
                'latitudeString']
            OrderStr['longitudeDefault'] = self.currentOrder_response_data['lastOderInfo']['address'][
                'longitudeString']
            OrderStr['longitudeString'] = self.currentOrder_response_data['lastOderInfo']['address'][
                'longitudeString']
            OrderStr['orvp'] = ''  # 这个参数暂时不知怎么来
            OrderStr['plusExposureCount'] = 2,
            OrderStr['plusFloorClosedTimeStamp'] = ''
            OrderStr['plusJdkClosedTimeStamp'] = ''
            OrderStr['rechargeList'] = []
            OrderStr['retainTipsNumber'] = 0
            OrderStr['redpacket_channel'] = 'JD'
            OrderStr['submitTransferJson'] = self.currentOrder_response_data['lastOderInfo']['submitTransferJson']
            OrderStr['time'] = int(time.time() * 1000)
            OrderStr['venderRemarkList'] = []
            data = {
                'AppKeplerParams': {'otherData': {'mopenbp5': ''}},
                'CartStr': {},
                'OrderStr': OrderStr,
                'SupportJdBean': True,
                'appEID': self.eid,
                'biometricSDKToken': self.x_api_eid_token,
                'cartuuid': self.cartUUID,
                'decryptType': '2',
                'fk_appId': 'com.jingdong.app.mall',
                'fk_latitude': self.Lat,
                'fk_longtitude': self.lng,
                'fk_terminalType': '02',
                'fk_traceIp': '10.1.10.1',
                'jdvTime': str(int(time.time()) * 1000),
                'orderUnion': {},
                'settlementVersionCode': 1800,
                'statisticsStr': {},
                'supportAllEncode': True,
                'supportNewParamEncode': True,
                'syntype': '1',
                'unpl': '',
                'transferJson': self.currentOrder_response_data['lastOderInfo']['transferJson'],

            }
            body = dict_json(data)
            self.submitOrderSign = getSign(functionId='submitOrder', body=body, client='android',
                                           clientVersion=self.clientVersion, uuid=self.uuid)
            self.submitPayloadBody = body
        except Exception as e:
            self.ui.console.append("{0}   结算哥哥偷懒...请求订单结算数据失败.请更换ip重试".format(get_current_time()))
            return

    # 构建生成订单所需body数据（定金预售）
    def submit_data_deposit(self, sku):
        """
        定金数据
        :param sku:
        :return:
        """
        OrderStr = dict()
        orderUnion = dict()
        OrderStr['Id'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['Id']
        OrderStr['IdArea'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdArea']
        OrderStr['IdCity'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdCity']
        OrderStr['IdProvince'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdProvince']
        OrderStr['IdTown'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['IdTown']
        OrderStr['Mobile'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['MobileReal']
        OrderStr['Name'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['Name']
        OrderStr['Where'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['Where']
        OrderStr['addressDetail'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['addressDetail']
        OrderStr[
            'aiRiskOrderEmbeddig'] = '0|22|A00|Kb2|C0y|KCR|CJτ|Ccs|MόI|MDϏ|C2u|Bνη|MBϒ|Cσt|Crβ|MBν|MUp|Bϕd|C7ς|10|00|0|O|σ|p'
        OrderStr['inputPasswordExplain'] = '请输入6位数字密码'
        OrderStr['isDjGlobalAddressCharge'] = False
        OrderStr['isFriendPayForMeSubmit'] = False
        OrderStr['isIdCardVerifyRequired'] = False
        OrderStr['isLimitBuyVender'] = False
        OrderStr['isNeedVirtualData'] = True
        OrderStr['isNotChoseConsolidatorShop'] = False
        OrderStr['isOpenPaymentPassword'] = True
        OrderStr['isPayForMeSubmit'] = False
        OrderStr['isShortPwd'] = True
        OrderStr['latitudeDefault'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['latitudeString']
        OrderStr['latitudeString'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['latitudeString']
        OrderStr['longitudeDefault'] = self.currentOrder_response_data[sku]['lastOderInfo']['address'][
            'longitudeString']
        OrderStr['longitudeString'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['longitudeString']
        OrderStr['notifyMobile'] = self.currentOrder_response_data[sku]['lastOderInfo']['address']['MobileReal']
        OrderStr['orvp'] = ''  # 这个参数暂时不知怎么来
        OrderStr['plusExposureCount'] = 0,
        OrderStr['plusFloorClosedTimeStamp'] = ''
        OrderStr['presaleStepPay'] = '2'
        OrderStr['retainTipsNumber'] = 0
        OrderStr['redpacket_channel'] = 'JD'
        OrderStr['submitTransferJson'] = self.currentOrder_response_data[sku]['lastOderInfo']['submitTransferJson']
        OrderStr['time'] = int(time.time() * 1000)
        OrderStr['venderRemarkList'] = []
        # orderUnion['advertise_app'] = ''
        # orderUnion['appkey'] = '1b41a7042ce724d9ecaa5a15fe9fab7a'
        # orderUnion['channel_id'] = 'wandoujia'
        # orderUnion['fe_order_track'] = ''
        # orderUnion['union_id'] = '50966'
        # orderUnion['uuid'] = self.uuid

        data = {
            'AppKeplerParams': {'otherData': {'mopenbp5': ''}},
            'CartStr': {'TheSkus': [{'Id': sku, 'num': '1'}]},
            'OrderStr': OrderStr,
            'SupportJdBean': True,
            'appEID': self.eid,
            'biometricSDKToken': self.x_api_eid_token,  # 该参数有对应接口请求，但是具体提交参数不是很清楚
            'cartuuid': str(uuid.uuid4()),
            'decryptType': '2',
            'fk_appId': 'com.jingdong.app.mall',
            'fk_latitude': self.Lat,
            'fk_longtitude': self.lng,
            'fk_terminalType': '02',
            'fk_traceIp': '10.1.10.1',
            'isPresale': True,
            'jdvTime': str(int(time.time()) * 1000),
            # 'm_param': '',
            # 'm_paramTime': str(int(time.time()) * 1000),
            'orderUnion': {},
            # 'se': '',
            'settlementVersionCode': 2540,
            # 'si': '',
            'supportAllEncode': True,
            'supportNewParamEncode': True,
            'syntype': '1',
            'transferJson': self.currentOrder_response_data[sku]['lastOderInfo']['transferJson'],
        }
        body = dict_json(data)
        self.submitOrderSign = getSign(functionId='submitOrder', body=body, client='android',
                                       clientVersion=self.clientVersion, uuid=self.uuid)
        self.submitPayloadBody = body

    # 提交订单
    def submitOrder(self, sku, num):
        body = self.submitPayloadBody
        functionId = 'submitOrder'
        sign = self.submitOrderSign
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body)
        self.ui.console.append("{0}   开始提交订单".format(get_current_time()))
        try:
            resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
            resp_text = json.loads(resp.text)
            if resp_text.get('code') and resp_text['code'] == '605':
                self.ui.console.append('{0}   {1}'.format(get_current_time(), '验证一下，购物无忧'))
                return False
            if resp_text.get('inputPassword'):
                self.ui.console.append(
                    "{0}   检测到账户勾选了虚拟资产,需要支付密码.本次下单失败".format(get_current_time()))
                return False
            if resp_text.get('tips'):
                self.ui.console.append(
                    "{0}   {1}".format(get_current_time(), resp_text['tips']))
                return False
            if resp_text.get('coMsg'):
                self.ui.console.append("{0}   恭喜抢购成功".format(get_current_time()))
                if self.send_message:
                    key = global_config.get('messenger', 'sckey')
                    params = {
                        'text': '{0}抢购成功下单提醒'.format(self.user),
                        'desp': '恭喜:' + self.user + '成功下单,快去付款吧'
                    }
                    requests.get(url='https://sctapi.ftqq.com/{0}.send'.format(key), params=params)
                    self.getPayChannel(orderId=resp_text['submitOrder']['OrderId'],
                                       orderType=resp_text['submitOrder']['OrderType'],
                                       totalPrice=resp_text['submitOrder']['Price'])
                    return True
                else:
                    self.getPayChannel(orderId=resp_text['submitOrder']['OrderId'],
                                       orderType=resp_text['submitOrder']['OrderType'],
                                       totalPrice=resp_text['submitOrder']['Price'])
                    return True
            else:
                self.ui.console.append(
                    "{0}   {1}".format(get_current_time(), resp_text['submitOrder']['Message']))
                return False

        except Exception:
            self.ui.console.append("{0}   提交订单发生错误.").format(get_current_time())
            return False

    # 获取支付方式
    def getPayChannel(self, orderId, orderType, totalPrice):
        if not self.initLogin:
            self.ui.console.append("{0}   app缓存无效。提取代付流程终止.").format(get_current_time())
            return
        orderId = str(orderId)
        orderType = str(orderType)
        if isinstance(totalPrice, float):
            totalPrice = format(totalPrice, '.2f')
        functionId = 'platPayChannel'
        body = {
            'appId': 'jd_android_app4',
            'client': 'android',
            'fk_aid': self.uuid,
            'fk_appId': 'com.jingdong.app.mall',
            'fk_latitude': self.Lat,
            'fk_longtitude': self.lng,
            'fk_terminalType': '02',
            'fk_traceIp': '172.16.39.15',
            'hasAndroidPay': '0',
            'hasCyberMoneyPay': '0',
            'hasHUAWEIPay': '0',
            'hasOCPay': '0',
            'hasUPPay': '0',
            'orderId': orderId,
            'orderPrice': totalPrice,
            'orderType': orderType,
            'orderTypeCode': '0',
            'origin': 'native',
            'paySourceId': '0',
            'payablePrice': totalPrice,
            'platPayCashierType': '0',
            'source': 'jdapp',
            'style': 'normal',
            'submitOrderExtFlag': {'isGoodsDetailJinCaiFlag': '', 'payPath': '2'},
            'supportNFC': '1'
        }
        paySign = get_paysiyn(orderid=orderId, ordertype=orderType, factprice=totalPrice)
        body['paySign'] = paySign
        body = dict_json(body)
        sign = getSign(functionId=functionId, body=body, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '1',
            'networkType': 'UNKNOWN',
            'uemps': '0-0-999',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'avifSupport': '1',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body)
        resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
        resp_json = json.loads(resp.text)
        try:
            if resp_json.get('errorCode'):
                self.ui.console.append("{0}   很抱歉,订单已经被天网风控系统拦截取消".format(get_current_time()))
            else:
                self.platDFPay(orderId=orderId, orderType=orderType, totalPrice=totalPrice, payId=resp_json['payId'])
        except:
            self.ui.console.append("{0}   提取代付链接出现错误".format(get_current_time()))

    # 获取代付链接
    def platDFPay(self, orderId, orderType, totalPrice, payId):
        functionId = 'platDFPay'
        body = {
            'appId': 'jd_android_app4',
            'backUrl': 'null',
            'client': 'android',
            'orderId': orderId,
            'orderPrice': totalPrice,
            'orderType': orderType,
            'orderTypeCode': '',
            'origin': 'native',
            'payId': payId,
            'platPayCashierType': '0',
            'source': 'jdapp',
        }
        paySign = get_paysiyn(orderid=orderId, ordertype=orderType, factprice=totalPrice)
        body['paySign'] = paySign
        body = dict_json(body)
        sign = getSign(functionId=functionId, body=body, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '1',
            'networkType': 'UNKNOWN',
            'uemps': '0-0-999',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'avifSupport': '1',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body)
        resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
        resp_json = json.loads(resp.text)
        self.ui.console.append("{0}   微信代付链接->{1}".format(get_current_time(), resp_json['shareInfo']['shareUrl']))

    # 提交订单(定金)
    def submitOrder_deposit(self, sku):
        body = self.submitPayloadBody
        functionId = 'submitOrder'
        sign = self.submitOrderSign
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body
        }
        self.ui.console.append("{0}   开始提交订单".format(get_current_time()))
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body)
        resp = self.sess.post(url=url, headers=headers, params=params, data=payload)
        resp_text = json.loads(resp.text)
        if resp_text.get('coMsg'):
            self.ui.console.append("{0}   恭喜抢购成功".format(get_current_time()))
            if self.send_message:
                key = global_config.get('messenger', 'sckey')
                params = {
                    'text': '{0}抢购成功下单提醒'.format(self.user),
                    'desp': '恭喜:' + self.user + '成功下单:' + sku + ',快去付款吧'
                }
                requests.get(url='https://sctapi.ftqq.com/{0}.send'.format(key), params=params)
                self.getPayChannel(orderId=resp_text['submitOrder']['OrderId'],
                                   orderType=resp_text['submitOrder']['OrderType'],
                                   totalPrice=resp_text['submitOrder']['Price'])
                return True
            else:
                self.getPayChannel(orderId=resp_text['submitOrder']['OrderId'],
                                   orderType=resp_text['submitOrder']['OrderType'],
                                   totalPrice=resp_text['submitOrder']['Price'])
                return True
        else:
            self.ui.console.append(
                "{0}   {1}".format(get_current_time(), resp_text['submitOrder']['Message']))
            return False

    def submitOrder_byTime(self, sku, buy_time, num):
        """
        定时提交加车商品订单
        :return:
        """
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        pre = Timer(buy_time=buy_time)
        pre.pre_start()
        # self.currentOrderSkuPack()
        if not self.currentOrder(sku=sku, num=num):
            return
        t = Timer(buy_time=buy_time)
        t.start()
        if self.submitOrder(sku=sku, num=num):
            return True
        else:
            return False

    def submitOrder_skuPack_byTime(self, sku, buy_time, num):
        """
        定时提交加车商品订单（多商品）
        :return:
        """
        if not self.cart():
            return
        # 先清空购物车
        self.batchDelete()
        # 再逐个添加商品到购物车
        for i in sku:
            self.cartAdd(i)
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        t = Timer(buy_time=buy_time)
        t.start()
        # 一键全选
        if not self.cartCheckAll():
            return
        if not self.currentOrderSkuPack():
            return
        if self.submitOrder(sku=sku, num=num):
            return True
        else:
            return False

    def submitOrder_byTime_notPre(self, sku, buy_time, num):
        """
        定时提交加车商品订单
        :return:
        """
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        t = Timer(buy_time=buy_time)
        t.start()
        if not self.currentOrder(sku=sku, num=num):
            return
        if self.submitOrder(sku=sku, num=num):
            return True
        else:
            return False

    def submitOrder_deposit_byTime(self, sku, buy_time):
        """
        定时提交定金商品订单
        :return:
        """
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        t = Timer(buy_time=buy_time)
        t.start()
        if not self.currentOrder_deposit(sku=sku):
            return
        if self.submitOrder_deposit(sku=sku):
            return True
        else:
            return False

    # 跳转抢购模式商品抢购链接
    def app_jump(self, sku):
        jump = self.getToken(url='https://divide.jd.com/user_routing?skuId={0}&from=app&deliveryMode=null'.format(sku))
        url = jump[1]
        params = {
            'to': 'https://divide.jd.com/user_routing?skuId=' + sku + '&from=app&deliveryMode=null',
            'tokenKey': jump[0],
            'sceneid': 25
        }
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
            'Host': 'un.m.jd.com'
        }
        resp = self.sess.get(url=url, headers=headers, params=params, allow_redirects=False)
        jump_url = resp.headers['location']
        seckill_url = jump_url.replace('divide', 'marathon').replace('user_routing', 'm/captcha.html')
        return seckill_url

    # 获取抢购模式商品抢购链接
    def get_seckill_url(self, sku):
        self.seckill_url[sku] = self.app_jump(sku=sku)

    def request_seckill_url(self, sku):
        if not self.seckill_url.get(sku):
            self.get_seckill_url(sku=sku)
        """访问商品的抢购链接（用于设置cookie）
        """
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
            'Host': 'marathon.jd.com'
        }
        while True:
            try:
                resp = self.sess.get(url=self.seckill_url.get(sku), headers=headers, allow_redirects=False)
                if resp.headers['location'] == 'https://marathon.jd.com/mobile/koFail.html':
                    self.ui.console.append(
                        "{0}   访问商品抢购链接失败.可能商品当前不是抢购模式商品或服务器数据未刷新.准备重新请求".format(
                            get_current_time()))
                    QApplication.processEvents()
                    QtTest.QTest.qWait(100)
                else:
                    self.ui.console.append("{0}   访问商品抢购链接成功".format(get_current_time()))
                    return
            except Exception:
                self.ui.console.append("{0}   访问商品抢购链接出错".format(get_current_time()))

    def frist_step(self, sku):
        functionId = 'lv'
        body = r'{"comefrom":"isko","ft":null,"murl":null,"number":"1","skuId":"' + sku + '"}'
        sign = getSign(functionId=functionId, body=body, client=self.client, clientVersion=self.clientVersion,
                       uuid=self.uuid)
        result = sign.split('&')
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'User-Agent': self.userAgent,
            'X-Rp-Client': 'android_4.0.0',
            'X-Referer-Package': 'com.jingdong.app.mall',
            'charset': 'UTF-8',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'x-httpdns-route': '111.202.127.106',
            'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
            'accept-encoding': 'br,gzip,deflate',
            'x-pp-aew': '68',
            'cache-control': 'no-cache'
        }
        params = {
            'functionId': functionId,
            'clientVersion': self.clientVersion,
            'build': '100533',
            'client': 'android',
            'partner': 'jingdong',
            'sdkVersion': '25',
            'lang': 'zh_CN',
            'harmonyOs': '0',
            'networkType': 'UNKNOWN',
            'uemps': '0-1-0',
            'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
            'eid': self.eid,
            'x-api-eid-token': self.x_api_eid_token,
            'xAPINqe': '1',
            'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
            'xAPIClientLanguage': 'zh_CN',
            'xAPINeoType': '999',
            'ef': '1',
            'uts': self.uts,
            'ep': self.ep,
            'st': result[0].split('=')[1],
            'sign': result[1].split('=')[1],
            'sv': '111'
        }
        payload = {
            'body': body
        }
        query_string = urlencode(params)
        full_url = urljoin('/client.action', '?' + query_string)
        headers['jdgs'] = self.jdGsService.getJdgs(self.eid, full_url, body)
        self.sess.post(url=url, headers=headers, params=params, data=payload)

    # 抢购模式订单地址初始化
    def address_init(self, sku, num):
        url = 'https://marathon.jd.com/seckillnew/orderService/init.action'
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
            'Host': 'marathon.jd.com',
            'Origin': 'https://marathon.jd.com',
            'Referer': 'https://marathon.jd.com/seckillM/seckill.action?skuId={0}&num=1&rid={1}&deliveryMode=null'.format(
                sku, int(
                    time.time()))
        }
        payload = {
            'sku': sku,
            'num': num,
            'deliveryMode': 'null',
            'id': 0,
            'provinceId': 1,
            'cityId': 72,
            'countyId': 2799,
            'townId': 0

        }
        while True:
            resp = self.sess.post(url=url, data=payload, headers=headers, allow_redirects=False)
            if resp.text == 'null' or resp.text == '':
                self.ui.console.append("{0}   服务器没有返回所需数据,尝试重新请求".format(get_current_time()))
            else:
                if json_format(raw_msg=resp.text):
                    self.ui.console.append("{0}   服务器成功响应".format(get_current_time()))
                    return json.loads(resp.text)
                else:
                    self.ui.console.append("{0}   服务器没有返回所需数据,尝试重新请求".format(get_current_time()))

    # 构建抢购模式商品预提交订单数据
    def _gen_seckill_order_data(self, sku, num):
        # if not self.seckill_init_info.get(sku):
        #     self.seckill_init_info[sku] = self.address_init(sku=sku, num=num)
        self.seckill_init_info[sku] = self.address_init(sku=sku, num=num)
        init_info = self.seckill_init_info.get(sku)
        if init_info.get('addressList'):
            default_address = init_info['addressList'][0]
        else:
            default_address = init_info['address']
        invoice_info = init_info.get('invoiceInfo', {})
        token = init_info['token']
        data = {
            'num': num,
            'addressId': default_address['id'],
            'name': default_address['name'],
            'provinceId': default_address['provinceId'],
            'provinceName': default_address['provinceName'],
            'cityId': default_address['cityId'],
            'cityName': default_address['cityName'],
            'countyId': default_address['countyId'],
            'countyName': default_address['countyName'],
            'townId': default_address['townId'],
            'townName': default_address['townName'],
            'addressDetail': default_address['addressDetail'],
            'mobile': default_address['mobile'],
            'mobileKey': default_address['mobileKey'],
            'email': '',
            'invoiceTitle': invoice_info.get('invoiceTitle', -1),
            'invoiceContent': invoice_info.get('invoiceContentType', 1),
            'invoicePhone': invoice_info.get('invoicePhone', ''),
            'invoicePhoneKey': invoice_info.get('invoicePhoneKey', ''),
            'invoice': 'true' if invoice_info else 'false',
            'password': '',
            'codTimeType': 3,
            'paymentType': 4,
            'overseas': 0,
            'phone': '',
            'areaCode': default_address['areaCode'],
            'token': token,
            'skuId': sku,
        }
        return data

    # 抢购模式京东预防机器下单sk加密参数
    def get_sk(self, sku):
        url = 'https://tak.jd.com/t/871A9?_t=' + str(int(time.time() * 1000))
        headers = {
            'Accept': '*/*',
            'User-Agent': 'jdapp;android;' + self.clientVersion + ';11;;network/UNKNOWN;model/TAS-AN00;addressid/' + self.addressid + ';aid/' + self.uuid + ';oaid/;osVer/30;appBuild/88136;partner/tencent;eufv/1;jdSupportDarkMode/0;Mozilla/5.0 (Linux; U; Android 7.1.2; TAS-AN00 Build/TAS-AN00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045710 Mobile Safari/537.36',
            'X-Requested-With': 'com.jingdong.app.mall',
            'Host': 'tak.jd.com',
            'Origin': 'https://marathon.jd.com',
            'Referer': 'https://marathon.jd.com/seckillM/seckill.action?skuId={0}&num=1&rid={1}'.format(sku, int(
                time.time()))
        }
        resp = self.sess.get(url=url, headers=headers)
        return sk_sign(resp=json.loads(resp.text))

    # h5st算法签名生成
    def get_h5st_v43(self, signStr, ai, date, ts, key):
        extra = {
            'sua': 'Linux; Android 11; HUAWEI Build/RP1A.200720.012; wv',
            'pp': {
                'p1': self.user,
                'p2': self.user
            },
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': -1,
                'bu3': 37,
                'bu4': 0
            },
            'random': generate_random_string(10),
            'v': 'h5_file_v4.3.3',
            'fp': self.h5stEncryptInfo[ai]['fp']
        }
        tk = self.h5stEncryptInfo[ai]['tk']
        fp = self.h5stEncryptInfo[ai]['fp']
        sign = get_hmacsha256(key=key, data=signStr)
        return date + ';' + fp + ';' + ai + ';' + tk + ';' + sign + ';4.3;' + ts + ';' + self.aes_encrypt(
            body=json.dumps(extra), key='&d74&yWoV.EYbWbZ')

    # 抢购订单提交
    def sekill_submit(self, sku, num):
        date = get_date()[0]
        ts = get_date()[1]
        enctry_str = self.h5stEncryptInfo['9da72']['tk'] + self.h5stEncryptInfo['9da72']['fp'] + date + '22' + '9da72' + \
                     self.h5stEncryptInfo['9da72']['rd']
        """
        h5st签名动态key生成
        """
        key = self.get_h5st_signStr_key(ai='9da72', enctry_str=enctry_str)
        if not self.seckill_url.get(sku):
            self.request_seckill_url(sku=sku)
        self.seckill_order_data[sku] = self._gen_seckill_order_data(sku=sku, num=num)
        # if not self.seckill_order_data.get(sku):
        #     self.seckill_order_data[sku] = self._gen_seckill_order_data(sku=sku, num=num)
        signStr = 'appid:jx_h5' + '&body:' + get_sha256(
            data=self.seckill_order_data[sku]) + '&client:jxh5&clientVersion:1.2.5&functionId:jxt_miao_orderinfo'
        self.seckill_order_data[sku]['eid'] = self.x_api_eid_token
        self.seckill_order_data[sku][
            '_stk'] = 'addressDetail,addressId,areaCode,cityId,cityName,codTimeType,countyId,countyName,email,invoice,invoiceContent,invoicePhone,invoicePhoneKey,invoiceTitle,mobile,mobileKey,name,num,overseas,password,paymentType,phone,provinceId,provinceName,skuId,token,townId,townName'
        self.seckill_order_data[sku]['h5st'] = self.get_h5st_v43(signStr=signStr, ai='9da72', date=date, ts=ts, key=key)
        self.seckill_url[sku] = ''
        # sk = self.get_sk(sku=sku)
        # self.seckill_order_data[sku]['sk'] = sk
        url = 'https://marathon.jd.com/seckillnew/orderService/submitOrder.action?skuId=' + sku
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
            'X-referer-page': 'https://marathon.jd.com/seckillM/seckill.action',
            'X-Rp-Client': 'h5_1.0.0',
            'Host': 'marathon.jd.com',
            'Origin': 'https://marathon.jd.com',
            'Referer': 'https://marathon.jd.com/seckillM/seckill.action?skuId={0}&num=1&rid={1}&deliveryMode=null'.format(
                sku, int(
                    time.time()))
        }
        try:
            resp = self.sess.post(url=url, headers=headers, data=self.seckill_order_data.get(sku))
            resp_json = json.loads(resp.text)
        except Exception as e:
            self.ui.console.append("{0}   秒杀请求出错".format(get_current_time()))
            return False
        if resp_json.get('success'):
            self.ui.console.append("{0}   恭喜抢购成功".format(get_current_time()))
            if self.send_message:
                key = global_config.get('messenger', 'sckey')
                params = {
                    'text': '{0}抢购成功下单提醒'.format(self.user),
                    'desp': '恭喜:' + self.user + '成功下单:' + sku + '快去付款吧'
                }
                requests.get(url=' http://sctapi.ftqq.com/{0}.send'.format(key), params=params)
                self.getPayChannel(orderId=resp_json['orderId'],
                                   orderType=0,
                                   totalPrice=resp_json['totalMoney'])
                return True
            return True
        else:
            self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['errorMessage']))
            return False

    # 获取h5st算法token,对应加密算法，rd
    def get_seckill_h5stToken(self, sku):
        self.h5stEncryptInfo['9da72']['fp'] = get_fp43()
        expandParams = {
            'wc': 0,
            'wd': 0,
            'l': 'zh-CN',
            'ls': 'zh-CN,zh',
            'ml': 0,
            'pl': 0,
            'av': self.seckillUserAgent[self.seckillUserAgent.find("appBuild/") + len("appBuild/"):],
            'ua': self.seckillUserAgent,
            'sua': 'Linux; Android 11; HUAWEI Build/RP1A.200720.012; wv',
            'pp': {'p1': self.user, 'p2': self.user},
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': 0,
                'bu3': 37,
                'bu4': 0
            },
            'pp1': '',
            'w': 390,
            'h': 844,
            'ow': 390,
            'oh': 844,
            'url': 'https://marathon.jd.com/seckillM/seckill.action?skuId={0}&num=1&rid={1}&deliveryMode=null'.format(
                sku,
                int(time.time())),
            'og': 'https://marathon.jd.com',
            'pr': 3.75,
            're': '',
            'random': generate_random_string(10),
            'referer': '',
            'v': 'h5_file_v4.3.3',
            'ai': '9da72',
            'fp': self.h5stEncryptInfo['9da72']['fp']
        }
        algoHeaders = {
            'Host': 'cactus.jd.com',
            'Origin': 'https://marathon.jd.com',
            'Referer': 'https://marathon.jd.com',
            'User-Agent': self.seckillUserAgent,
            'Content-Type': 'application/json',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
        }
        algoPayload = {
            'version': '4.3',
            'fp': self.h5stEncryptInfo['9da72']['fp'],
            'fv': 'h5_file_v4.3.3',
            'appId': '9da72',
            'timestamp': str(round(time.time() * 1000)),
            'platform': 'web',
            'expandParams': self.aes_encrypt(body=json.dumps(expandParams), key='wm0!@w-s#ll1flo('),
        }
        self.get_h5st_token(ai='9da72', headers=algoHeaders, payload=algoPayload)

    def exec_seckill(self, sku, num):
        if self.sekill_submit(sku=sku, num=num):
            return True
        else:
            return False

    def seckill_byTime(self, sku, buy_time, num):
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        self.get_seckill_h5stToken(sku=sku)
        # pre = Timer(buy_time=buy_time)
        # pre.pre_start()
        t = Timer(buy_time=buy_time)
        t.start()
        # self.get_seckill_url(sku=sku)
        # self.frist_step(sku=sku)
        self.request_seckill_url(sku=sku)
        if self.exec_seckill(sku=sku, num=num):
            return True
        else:
            return False
